<template>
  <el-form ref="editForm" :rules="rules" :model="form" label-width="230px">
  <el-form-item label="sql字段">
      <el-table
        :data="cols"
        border
        style="width: 100%">
        <el-table-column
          prop="javaName"
          label="java类名">
        </el-table-column>
        <el-table-column
          prop="colName"
          label="列名">
        </el-table-column>
        <el-table-column
          prop="desc"
          label="注释">
          <template slot-scope="scope">
              <el-input v-model="scope.row.desc" placeholder="请输入内容"></el-input>
            </template>
        </el-table-column>
        <el-table-column
          prop="dataType"
          label="数据类型">
                  <template slot-scope="scope">
                        <el-input v-model="scope.row.dataType" placeholder="请输入内容"></el-input>
                      </template>
        </el-table-column>
        <el-table-column
          prop="tableName"
          label="表别名">
        </el-table-column>
      </el-table>
 </el-form-item>
    <el-form-item label="代码作者">
      <el-input v-model="form.author" style="width:95%;"></el-input>
    </el-form-item>
    <el-form-item label="是否启用Lombok注解">
      <el-switch v-model="form.enableLombok"></el-switch>
    </el-form-item>
    <el-form-item prop="mapperPackage" label="Mapper(Xml)的包名">
      <el-autocomplete
        v-model="form.mapperPackage"
        style="width:95%;"
        :fetch-suggestions="queryMapperPackage"
        @select="handleMapperPackageSelect"
        placeholder="例如：com.example.OrderMapper"
      >
        <el-select
          v-model="form.mapperLocationPrefix"
          style="width:110px;"
          slot="prepend"
          placeholder="请选择源码目录"
        >
          <el-option label="java" value="java"></el-option>
          <el-option label="resources" value="resources"></el-option>
        </el-select>
      </el-autocomplete>
      <help-tip
        content="生成的Mapper方法所在的Mapper.xml的包名，例如：com.example.OrderMapper，选择java或resources会在对应的源码根目录中去查找资源"
      ></help-tip>
    </el-form-item>
    <el-form-item label="同步生成控制器(java)的方法">
          <el-switch v-model="form.enableCreateCtl"></el-switch>
        </el-form-item>

     <el-form-item label="控制器基础路径" v-if="form.enableCreateCtl">
      <el-input v-model="form.ctlBasePath" style="width:95%;"></el-input>
    </el-form-item>
     <el-form-item label="控制器path" v-if="form.enableCreateCtl">
      <el-input v-model="form.ctlPath" style="width:95%;"></el-input>
    </el-form-item>
    <el-form-item label="控制器tag" v-if="form.enableCreateCtl">
      <el-input v-model="form.apiTag" style="width:95%;"></el-input>
    </el-form-item>
    <el-form-item label="接口名" v-if="form.enableCreateCtl">
      <el-input v-model="form.apiName" style="width:95%;"></el-input>
    </el-form-item>
    <el-form-item label="同步生成Mapper(java)的方法">
      <el-switch v-model="form.enableCreateDaoMethod"></el-switch>
    </el-form-item>
    <el-form-item label="是否启用分页查询" v-if="form.enableCreateDaoMethod">
      <el-switch v-model="form.enablePageQuery"></el-switch>
      <help-tip content="启用分页查询后，Mapper方法的返回值会被包装为Page类型，同时增加相应的分页参数"></help-tip>
    </el-form-item>
    <el-form-item v-if="form.enableCreateDaoMethod" label="Mapper(java)方法的参数类型">
      <el-radio-group v-model="form.daoMethodParamType">
        <el-radio label="map">Map（SQL动态参数作为Map的key）</el-radio>
        <el-radio label="bean">Java Bean（SQL动态参数作为Bean的Property）</el-radio>
        <el-radio label="single">多参数（SQL动态参数每个都作为一个独立方法参数）</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item
      v-if="form.enableCreateDaoMethod && form.daoMethodParamType == 'bean'"
      label="Mapper(java)方法参数DTO"
    >
      <el-input
        style="width:80%;"
        v-model="form.daoMethodParamDto"
        placeholder="例如：com.example.dto.XXXMethodParamsDto"
      ></el-input>
      <help-tip content="Mapper的方法参数Bean的引用位置，如不存在则会根据SQL动态参数自动生成。"></help-tip>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">生成代码</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import axios from "axios";
import _ from "lodash";
import HelpTip from "@/components/HelpTip";
export default {
  props: ["sql"],
  components: {
    HelpTip,
  },
  data() {
    return {
      showDynamicParamsDemo: false,
      userBasePkg: "",
      cols:[],
      bmMap:{},
      form: {
        enableLombok: false,
        enablePageQuery: false,
        enableCreateDaoMethod: false,
        enableCreateCtl: false,
        enableParseDynamicParams: true,
        author: "",
        fullPackage: "",
        mapperMethod: "",
        mapperPackage: "",
        mapperLocation: "",
        mapperLocationPrefix: "resources",
        daoMethodParamType: "bean",
        daoMethodParamDto: "",
        ctlBasePath:'',
        ctlPath:'',
        apiTag:'',
        apiName:''
      },
      rules: {
        mapperPackage: [
          {
            required: true,
            message: "Mapper文件的包名必须填写",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted: function () {
    axios.get("/api/sql/basepackage").then((res) => {
      this.userBasePkg = res;
    });
    this.getDesc();
  },
  watch: {
   sql: {
       handler(newValue, oldValue) {
           this.sql=newValue;
           console.log('update',newValue)
       },
       deep: true
   }
  },
  methods: {
    handleMapperMethodInput() {
      if (this.form.mapperMethod) {
        this.form.fullPackage =
          this.userBasePkg +
          ".dto." +
          _.upperFirst(this.form.mapperMethod) +
          "ResultDto";
        this.form.daoMethodParamDto =
          this.userBasePkg +
          ".dto." +
          _.upperFirst(this.form.mapperMethod) +
          "ParamDto";
      }
    },
    getSqlBm(col){
        let bm=this.bmMap[col.colName]
        return bm?bm:col.colName;
    },
    queryMapperPackage(queryString, cb) {
      axios
        .get("/api/ac/mapperxml", {
          params: {
            mapperLocationPrefix: this.form.mapperLocationPrefix,
            searchKey: this.form.mapperPackage,
          },
        })
        .then((res) => {
          if (res) {
            let options = res.map((v) => {
              return { value: v };
            });
            cb(options);
          }
        });
    },
    handleMapperPackageSelect(op) {
      this.form.mapperPackage = op.value;
    },
    getDesc(){
         let toHump = function(name) {
              return name.replace(/\_(\w)/g, function(all, letter){
                  return letter.toUpperCase();
              });
         }
        axios.post('/api/sql/getDesc',{
            sql:this.sql.select.sql
        }).then(res=>{
            let bmMap={};
            //重复列怎么处理？
            let colMap={};
            let indexOrder=0;
            this.cols=res.map(item=>{
                item.javaName=toHump(item.colName);
                if(colMap[item.colName]){
                    //字段重复
                    console.log('字段重复'+item.colName)
                    let bm = item.colName+"_"+indexOrder;
                    bmMap[bm]=item.colName+" as "+bm;
                    item.colName=bm;
                    indexOrder++;

                }else{
                    colMap[item.colName]=item.javaName;
                }
                return item;
            })
            this.bmMap=bmMap;
            console.log(1,this.cols)
        })
    },
    onSubmit() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.form.mapperLocation =
            this.form.mapperPackage;




            //添加字段注释，替换*字段
            let beans = this.sql.beans;

            beans.forEach(bean=>{
                let newCols = [];
                for(var j of bean.fields){
                    let jname = j.colName;
                    if(jname==='*'){
                        console.log('遇到*字段')
                        //填充字段
                        this.cols.filter(i=>j.alias===i.tableName).map(i=>{
                            return {
                                name: i.javaName,
                                type: i.dataType,
                                desc: i.desc,
                                importPackage: i.importPackage
                            }
                        }).forEach(i=>{
                            newCols.push(i);
                            console.log('补充字段',i)
                        })
                    }else{
                        let fcol = this.cols.find(i=>i.colName==jname)
                        if(fcol){
                            newCols.push({
                              name: fcol.javaName,
                              type: fcol.dataType,
                              desc: fcol.desc,
                              importPackage: fcol.importPackage
                            })
                        }else{
                            newCols.push(j);
                            console.log('没找到对应的字段',j,this.cols)
                        }
                    }
                }

                bean.fields=newCols;
                console.log(newCols)
            })

            let resultMapper=this.sql.resultMapper;
            let nrf=[];
            for(var rm of resultMapper.fields){
                if(rm.indexOf("*")==-1){
                    nrf.push(rm);
                }else{
                    let reg=/property="(.*?)"/;
                    console.log(rm)
                    let tname = rm.match(reg)
                    if(!tname){
                        console.log('没找到表别名')
                        continue;
                    }
                    tname=tname[1]
                    this.cols.filter(i=>tname==i.tableName).forEach(col=>{
                        nrf.push(`<result property="${col.javaName}" column="${col.colName}"></result>`)
                    })
                }
            }

            console.log(2,nrf)
            this.sql.resultMapper.fields=nrf;

            //替换重新生成sql查询字段
            var sqlstr= this.sql.select.sql;
            this.sql.select.sql="select "+this.cols.map(i=>i.tableName+"."+this.getSqlBm(i)).join(',')+" "+sqlstr.substr(sqlstr.indexOf('from'));

            //提交请求
            axios
              .post("/api/sql/genplus", {
                ast: this.sql,
                config: this.form,
              })
              .then((res) => {
                this.$message.success("代码已经成功生成");
                this.$emit("done");
              });

        } else {
          return false;
        }
      });
    },
  },
};
</script>
